<template>
  <a-input-search
      class="btn-top-search"
      v-model:value="pathValue"
      placeholder="请根据路径或者执行人搜索"
      enter-button="Search"
      size="large"
      @search="onSearch"
      allow-clear
  />
  <a-button style="margin-left:10px;margin-right:10px" type="primary" size="large" @click="addPathVisible">添加路径</a-button>
  <a-button type="primary" size="large" danger @click="batchDeletePath">批量删除</a-button>
  <a-table 
    style="margin-top:3px;"
    bordered
    :scroll="{y: 480 }"
    :pagination="pagination"
    :rowKey="record=>record.pathId" 
    size="middle"
    :row-selection="rowSelection"
    :dataSource="dataAll.dataSource" 
    :columns="columns"
  >
    <template #bodyCell="{ column,record }" >
        <template v-if="column.key === 'allowPath'">
          <a-tooltip placement="topLeft" color="cyan">
            <template #title>{{record.allowPath}}</template>
            <a-tag v-if="record.allowPath.length > 65" color="cyan"  style="width:100%;height:30px;line-height:25px;font-size:18px">
                {{`${record.allowPath.slice(0,65)}...`}}      
            </a-tag>
          </a-tooltip>
          
          <a-tag v-if="record.allowPath.length <= 65" color="cyan" style="height:30px;line-height:25px;font-size:18px">
            {{record.allowPath}}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'operation'">
            <a-button type="primary" style="margin-right:10px" @click="updatePathVisible(record)">修改</a-button>
            <a-popconfirm
              title="确定删除当前数据?"
              ok-text="Yes"
              cancel-text="No"
              @confirm="confirmDelete(record)"
              @cancel="cancel"
            >
            <!-- @click="deleteOne(record)"  -->
            <a-button type="primary" danger>删除</a-button>
            </a-popconfirm>          
        </template>
    </template>
  </a-table>

  <!-- 修改对话框 -->
  <a-modal v-model:visible="dataAll.updateVisible" title="修改网关允许通过路径" @ok="updatePathOk">
    <a-input v-model:value="dataAll.selectRecord.allowPath" size="large" placeholder="请输入通关地址" />
  </a-modal>
  <!-- 添加对话框 -->
  <a-modal v-model:visible="dataAll.addVisible" title="添加网关允许通过路径" @ok="addPathOk">
    <a-input v-model:value="dataAll.addPath" size="large" placeholder="请输入通关地址" />
  </a-modal>
</template>
<script>
  import { ref, reactive,onMounted} from 'vue';
  import { message } from "ant-design-vue";
  import {$http} from '@/utils/axios';
  export default {
    setup() {
      onMounted(()=>{
        getAllAllowPath();
      })

      let pathValue = ref('');
      let dataAll = reactive({
          "selectedRows":[],
          "selectRecord":{},
          "updateVisible":false,
          "addVisible":false,
          "addPath":"",
          "dataSource":[]          
      });
      //顶部所搜框
      function onSearch(){
        // message.success("success,"+pathValue.value);
        getAllAllowPath()
      };
      //数据
      let dataSource = []
      //列
      let columns = [
          {
            title: '序号',
            dataIndex: 'index',
            width: '8%',
            key: 'index',
            customRender: ({ text, record, index }) => {
                return `${ index + 1 }`;
            },
            sorter: {
              compare: (a, b) => a.pathId - b.pathId
            },
          },
          {
            title: '允许通过路径',
            dataIndex: 'allowPath',
            sorter: {
              compare: (a, b) => a.allowPath.length - b.allowPath.length,
            },
            sortDirections: ['descend', 'ascend'],
            key: 'allowPath',
            width: '50%',
          },
          {
            title: '执行人',
            dataIndex: 'operationPeople',
            key: 'operationPeople',
            width: '12%',
          },
          {
            title: '执行时间',
            dataIndex: 'operatorTime',
            key: 'operatorTime',
            width: '15%',
          },
          {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            width: '15%',
          },
      ];
      //选中行
      const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
          dataAll.selectedRows = selectedRows;
        },
        getCheckboxProps: record => ({
          disabled: record.operationPeople === 'Disabled User',
          // Column configuration not to be checked
          name: record.operationPeople,
        }),
      };
      //分页
      let pagination = reactive({
        pageNo: 1,
        pageSize: 10, // 默认每页显示数量
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '30', '40'], // 每页数量选项
        showTotal: total => `共 ${total} 条`, // 显示总数
        onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize), // 改变每页数量时更新显示
        onChange:(page,pageSize)=>onPageChange(page,pageSize),//点击页码事件
        total:0 //总条数
      });
      function onPageChange(page, pageSize) {
        pagination.pageNo = page;
        pagination.pageSize = pageSize
        getAllAllowPath();
      };
      //更改每页条数
      function onSizeChange(current, pageSize) {
        pagination.pageNo = 1
        pagination.pageSize = pageSize
        getAllAllowPath();
      };
      //请求数据
      function getAllAllowPath(){
          $http.get(`/gatewayConfig/getAllAllowPath/${pagination.pageNo}/${pagination.pageSize}?pathValue=${pathValue.value}`).then((result)=>{
            dataAll.dataSource = result.data.data;
            if(null===result.data.data || result.data.data.length==0){
              pagination.total = 0
            }else{
              pagination.total = result.data.data[0].totals
            }
            
          }).catch((err)=>{
            console.log("获取允许通过网关路径:"+err);
            message.error("获取允许通过网关路径失败");
          })
      };
      //批量删除
      function batchDeletePath(){
          if(dataAll.selectedRows.length <= 0){
              return message.warning("请选择有效的数据行!!!")
          }
          let batchDeleteArr = [];
          dataAll.selectedRows.forEach((val)=>{
            batchDeleteArr.push(val);
          })
          message.error("批量删除")
          console.log('batch delete data:',batchDeleteArr);
      }
      //单个删除
      const deleteOne = ((val)=>{
          console.log('单个删除:',val);
      })
      //确认删除
      const confirmDelete = e => {
        console.log("气泡框确认删除:",e);
        message.success('Click on Yes,the key is:' + e.pathId);

      };
      //取消
      const cancel = e => {
        console.log(e);
        message.error('取消操作');
      };


      //修改路径弹框
      function updatePathVisible(val){
          dataAll.selectRecord = val;
          dataAll.updateVisible = true;
      }
      //确定修改
      function updatePathOk(){
        console.log("修改后的值:",dataAll.selectRecord);
        message.success("修改成功")
        dataAll.updateVisible = false
      }

      //添加弹框
      function addPathVisible(){
        dataAll.addVisible = true
      }
      //确认添加
      function addPathOk(){
        if(dataAll.addPath == null || dataAll.addPath ===""){
          message.warn('路径不能为空')
          return
        }
        const reg = /^\/[a-zA-Z]/
        if(!reg.test(dataAll.addPath)){
          message.warn('请填写有效的路径,以 / 开头,且内容为大小写英文字母,不能以 , . ? 结尾')
          return
        }
        $http.post("/gatewayConfig/addAllowPath",{path:dataAll.addPath}).then((result)=>{
          if(result.data.data){
            dataAll.addVisible=false
            getAllAllowPath()
            message.success(`添加成功`)
          }else{
            message.error(`添加失败,${result.data.message}`)
          }
        }).catch((err)=>{
          message.error(`添加失败,${err}`)
        })
        
      }
      
      return {
        dataAll,
        dataSource,
        columns,
        rowSelection,
        pathValue,
        onSearch,
        pagination,
        batchDeletePath,
        deleteOne,
        updatePathVisible,
        updatePathOk,
        addPathVisible,
        addPathOk,
        confirmDelete,
        cancel,
        getAllAllowPath
      };
    },
  };
</script>
<style scoped>
  .btn-top-search{
    width: 60%;
  }
/* 修改表格的行高，默认 */
  /* /deep/ .ant-table-tbody > tr > td {
    padding: 5px!important;
  } */
</style>